package org.sciom

object ScIomCoroutine {
  def raiseError(state: ScIomState, description: ScIomSymbol, m: ScIomMessage) = {
    var e = state.lobby.rawGetSlot(state.symbolWithString("Exception"))
    
    if(e != null) {
      e = e.IOCLONE
      e.setSlotTo(state.symbolWithString("error"), description)
      if(m != null) {
        e.setSlotTo(state.symbolWithString("caughtMessage"), m)
      }
    }
    throw new ScIomException(e)
  }

  def rawPrintBackTrace(e: ScIomException) : Unit = {
    rawPrintBackTrace(e.error)
  }

  def rawPrintBackTrace(e: ScIomObject) : Unit = {
    if(e != null) {
      System.err.println(getBackTraceFor(e))
    }
  }

  def getBackTraceFor(e: ScIomException) : String = {
    getBackTraceFor(e.error)
  }

  def getBackTraceFor(e: ScIomObject) : String = {
    val buffer = new StringBuilder
    if(e != null) {
      val caughtMessage = e.rawGetSlot(e.state.symbolWithString("caughtMessage"))
      val error = e.rawGetSlot(e.state.symbolWithString("error"))

      if(error != null) {
        buffer.append(error.asInstanceOf[ScIomSymbol].string).append("")
      } else {
        buffer.append("error: [missing error slot in Exception object]")
      }
/*
	  if(caughtMessage != null) {
        buffer.append(caughtMessage.asInstanceOf[ScIomMessage].asMinimalStackEntryDescription).append("\n")
      }
*/
      buffer.toString
    } else {
      ""
    }
  }
}
